package com.sanjiahantang.ythshopping.activity.me;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.sanjiahantang.ythshopping.R;
import com.sanjiahantang.ythshopping.activity.BaseActivity;
import com.sanjiahantang.ythshopping.activity.GoodsFilterActivity;
import com.sanjiahantang.ythshopping.activity.MainActivity;
import com.sanjiahantang.ythshopping.alipay.PayResult;
import com.sanjiahantang.ythshopping.config.ConfigValue;
import com.sanjiahantang.ythshopping.config.SPConfig;
import com.sanjiahantang.ythshopping.model.AliPatModel;
import com.sanjiahantang.ythshopping.model.WXpayModel;
import com.sanjiahantang.ythshopping.model.WebPayModel;
import com.sanjiahantang.ythshopping.presenter.PayActivePresenter;
import com.sanjiahantang.ythshopping.presenter.WebPayPresenter;
import com.sanjiahantang.ythshopping.qrzxing.CaptureActivity;
import com.sanjiahantang.ythshopping.utils.DataCleanManager;
import com.sanjiahantang.ythshopping.utils.SPUtils;
import com.sanjiahantang.ythshopping.views.PayActiveView;
import com.sanjiahantang.ythshopping.views.WebPayView;
import com.sanjiahantang.shopping.uilibrary.uiutils.Utils;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.socialize.facebook.controller.utils.ToastUtil;

import java.util.Map;

/**
 * Created by admin on 2017/8/14.
 */

public class JsWebActivity extends BaseActivity implements View.OnClickListener,WebPayView,PayActiveView {

    private WebView wv_js;
    private View errorView;
    private boolean isHttp = false;
    private RadioGroup radioGroup;
    private String mIntentURL;
    public static final String TAG = "JsWebActivity";
    public int paytype=1;//1：支付宝
    WebPayPresenter webPayPresenter;
    private static final int SDK_PAY_FLAG = 1;

    private static final int SDK_CHECK_FLAG = 2;

    String aliinfo="";
    private boolean loadError = false;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);

                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    String resultInfo = payResult.getResult();

                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Intent intent=new Intent(JsWebActivity.this, MainActivity.class);
                        startActivity(intent);
                        com.sanjiahantang.ythshopping.utils.Utils.showToast(JsWebActivity.this, "支付成功");
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            com.sanjiahantang.ythshopping.utils.Utils.showToast(JsWebActivity.this,"支付结果确认中");
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            com.sanjiahantang.ythshopping.utils.Utils.showToast(JsWebActivity.this, "支付失败");
                        }
                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                    if (!(boolean) msg.obj)
                        com.sanjiahantang.ythshopping.utils.Utils.showToast(JsWebActivity.this, "检查结果为：" + msg.obj);
                    else {

                    }
                    break;
                }
                default:
                    break;
            }
        };
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    private View rbHome,rbCategory,rbnearby,rbShoppingCart,rbMe;
    public static final int REQUEST_CODE = 0x0009;

    @Override
    public void initView() {
        super.initView();
        setContentView(R.layout.activity_jsweb);

        radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
        rbHome = findViewById(R.id.rbHome);
        rbCategory = findViewById(R.id.rbCategory);
        rbnearby = findViewById(R.id.rbnearby);
        rbShoppingCart = findViewById(R.id.rbShoppingCart);
        rbMe = findViewById(R.id.rbMe);
        webPayPresenter=new WebPayPresenter(mContext,this);
        errorView = findViewById(R.id.errorView);




        wv_js= (WebView) findViewById(R.id.wv_jsweb);

        wv_js.setWebViewClient(new webViewClient());
        wv_js.setWebChromeClient(new webChromeClient());


        WebSettings settings = wv_js.getSettings();
        settings.setJavaScriptEnabled(true);//启用js
        settings.setJavaScriptCanOpenWindowsAutomatically(true);//js和android交互
        settings.setAllowFileAccess(true); // 允许访问文件
        settings.setAppCacheEnabled(true); //设置H5的缓存打开,默认关闭
        settings.setUseWideViewPort(true);//设置webview自适应屏幕大小
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);//设置，可能的话使所有列的宽度不超过屏幕宽度
        settings.setLoadWithOverviewMode(true);//设置webview自适应屏幕大小
        settings.setDomStorageEnabled(true);//设置可以使用localStorage
        settings.setSupportZoom(false);//关闭zoom按钮
        settings.setBuiltInZoomControls(false);//关闭zoom

        //启用数据库
        settings.setDatabaseEnabled(true);

        //设置定位的数据库路径
        String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        settings.setGeolocationDatabasePath(dir);

        //启用地理定位
        settings.setGeolocationEnabled(true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            wv_js.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }


        wv_js.addJavascriptInterface(this, "");

        String path = getIntent().getStringExtra("url");
        mIntentURL = ConfigValue.IMG_IP + path;
        if(path.toLowerCase().contains("http://") || path.toLowerCase().contains("https://")){
            mIntentURL = path;
            isHttp = true;
        }else{
            mIntentURL = ConfigValue.IMG_IP + path;

            String state = "from_app=2&key=" + ConfigValue.DATA_KEY
                    + "&rid=" + ConfigValue.rid;
            if(mIntentURL.contains("?")){
                mIntentURL = mIntentURL + "&" + state;
            }else{
                mIntentURL = mIntentURL + "?" + state;
            }
        }





        wv_js.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_BACK && wv_js.canGoBack()) {  //表示按返回键


                        wv_js.goBack();   //后退

                        //webview.goForward();//前进
                        return true;    //已处理
                    }
                }
                return false;
            }
        });


        rbHome.setOnClickListener(this);
        rbCategory.setOnClickListener(this);
        rbnearby.setOnClickListener(this);
        rbShoppingCart.setOnClickListener(this);
        rbMe.setOnClickListener(this);
        if (mIntentURL.contains("mobile/user.php?act=default"))
        {
            radioGroup.check(R.id.rbMe);
            rbMe.setEnabled(false);
        }else {
            rbMe.setEnabled(true);

            switch (getIntent().getIntExtra("index",2)){
                case 0:
                    radioGroup.check(R.id.rbHome);
                    break;
                case 1:
                    radioGroup.check(R.id.rbCategory);
                    break;
                case 2:
                    radioGroup.check(R.id.rbnearby);
                    break;
                case 3:
                    radioGroup.check(R.id.rbShoppingCart);
                    break;
                case 4:
                    radioGroup.check(R.id.rbMe);
                    break;
            }
        }
        syncCookie(JsWebActivity.this, mIntentURL);
        wv_js.loadUrl(mIntentURL);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)  {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { //按下的如果是BACK，同时没有重复
            JsWebActivity.this.finish();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @JavascriptInterface
    public void sysao(int length){
        ToastUtil.showToast(JsWebActivity.this,"aaaaaaaaaaaa");
    }

    @Override
    public void initTitle() {
        super.initTitle();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==RESULT_OK)
        {
            if (requestCode==1)
            {

                final String msg=data.getStringExtra("suppid");
                wv_js.post(new Runnable() {
                    @Override
                    public void run() {


                        // 注意调用的JS方法名要对应上
                        // 调用javascript的callJS()方法
                        wv_js.loadUrl("javascript:scan_return("+msg+")");
                    }
                });
            }
        }
    }

    @Override
    public void onClick(View v) {
        int index = 0;
        switch (v.getId()){
            case R.id.rbHome:
                index = 0;
                break;
            case R.id.rbCategory:
                index = 1;
                break;
            case R.id.rbnearby:
                index = 2;
                break;
            case R.id.rbShoppingCart:
                index = 3;
                break;
            case R.id.rbMe:
                index = 4;
                break;

        }


        onLoadAndroidPage(index);


    }


    private void onLoadAndroidPage(int index){
        setResult(RESULT_OK,new Intent().putExtra("index",index));
        JsWebActivity.this.finish();
        overridePendingTransition(0, 0);

    }

    @Override
    public void rePayMsg(WebPayModel model) {
        PayActivePresenter payActivePresenter=new PayActivePresenter(this,mContext,model.getData(),model.getData().getSid()+"");
        if (paytype==1)
        {
            payActivePresenter.LoadsqAliPay();
        }else
        {
            payActivePresenter.LoadSQWXPay();
        }

    }

    @Override
    public void getWXinfo(WXpayModel wxpay) {
        if (wxpay.getCode().equals("1")) {
            final IWXAPI api = WXAPIFactory.createWXAPI(this, null);
            // 将该app注册到微信
            api.registerApp(ConfigValue.WXAPP_ID);

            PayReq req = new PayReq();

            req.appId = wxpay.getData().getPayinfo().getAppId();

            req.partnerId = wxpay.getData().getPayinfo().getPartnerId();
            req.prepayId = wxpay.getData().getPayinfo().getPrepayId();
            req.packageValue = "Sign=WXPay";
            req.nonceStr = wxpay.getData().getPayinfo().getNonceStr();
            req.timeStamp = wxpay.getData().getPayinfo().getTimeStamp();
            req.sign = wxpay.getData().getPayinfo().getSign();
            api.sendReq(req);


            finish();
        }else {
            Toast.makeText(this,wxpay.getMsg(),Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void getALiinfo(AliPatModel ali) {
        aliinfo=ali.getData().getPayinfo();
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
    Runnable payRunnable = new Runnable() {

        @Override
        public void run() {
            PayTask alipay = new PayTask(JsWebActivity.this);
            String result = alipay.pay(aliinfo);

            Message msg = new Message();
            msg.what = SDK_PAY_FLAG;
            msg.obj = result;
            mHandler.sendMessage(msg);
        }
    };

    // 继承自Object类
    public class AndroidtoJs extends Object {

        // 定义JS需要调用的方法
        // 被JS调用的方法必须加入@JavascriptInterface注解
        @TargetApi(Build.VERSION_CODES.M)
        @JavascriptInterface
        public void scan() {


            if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                requestPermissions(new String[]{Manifest.permission.CAMERA}, 1);

            } else {
                Intent itCapture = new Intent(JsWebActivity.this, CaptureActivity.class);
                itCapture.putExtra("type","web");
                startActivityForResult(itCapture,1);
                //startActivity(itCapture);

            }


        }
    }

    //Web视图
    private class webViewClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            loadError = false;
            super.onPageStarted(view, url, favicon);
        }

        public boolean shouldOverrideUrlLoading(WebView view, String url) {


            if (url.startsWith("tel:")) {
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
                startActivity(intent);
                return true;
            }



            if (Build.VERSION.SDK_INT >= 23) {
                int checkPermission = ContextCompat.checkSelfPermission(JsWebActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION);
                    if (checkPermission != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(JsWebActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
                    ActivityCompat.requestPermissions(JsWebActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
                    Log.d("TTTT", "弹出提示");
                }
            }

            if(isHttp){
                return super.shouldOverrideUrlLoading(view,url);
            }
            String lowerUrl = url.toLowerCase();


            //分类
            if (lowerUrl.contains("/category.php")){
                Intent mIntent = new Intent(JsWebActivity.this,GoodsFilterActivity.class);
                Map map = Utils.URLRequest(url);
                mIntent.putExtra("id",map.get("id").toString());
                startActivity(mIntent);
                return true;
            }

            //分类
            if (lowerUrl.contains("/catalog.php")){
//                startActivity(new Intent(JsWebActivity.this, MainActivity.class).putExtra("index",1));
                onLoadAndroidPage(1);
                return true;
            }
            //首页
            if (lowerUrl.contains("/index.php") || lowerUrl.endsWith("mobile/") || lowerUrl.contains("mobile/?")){
//                startActivity(new Intent(JsWebActivity.this, MainActivity.class).putExtra("index",0));
                onLoadAndroidPage(0);
                return true;
            }

            //购物车
            if (lowerUrl.contains("/flow.php")){
//                startActivity(new Intent(JsWebActivity.this, MainActivity.class).putExtra("index",3));
                onLoadAndroidPage(3);
                return true;
            }

            //用户
            if (lowerUrl.contains("/user.php")){
                Map map = Utils.URLRequest(url);
                if(lowerUrl.contains("act=relogin")){

                    if (!ConfigValue.DATA_KEY.equals("")) {
                        com.sanjiahantang.ythshopping.utils.Utils.showDialog(JsWebActivity.this, "提示", "确定退出登录吗？", "", "", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                switch (view.getId()) {
                                    case R.id.txtDialogCancel:
                                        com.sanjiahantang.ythshopping.utils.Utils.dismissDialog();
                                        break;
                                    case R.id.txtDialogSure:
                                        ConfigValue.uInfor = null;
                                        ConfigValue.DATA_KEY = "";
                                        SPUtils.remove(JsWebActivity.this, SPConfig.KEY);

                                        DataCleanManager.cleanApplicationData(JsWebActivity.this, "/data/data/"
                                                + JsWebActivity.this.getPackageName());
                                        com.sanjiahantang.ythshopping.utils.Utils.dismissDialog();
                                        startActivity(new Intent(JsWebActivity.this, LoginActivity.class));
                                        JsWebActivity.this.finish();
                                        break;
                                }
                            }
                        });
                    }
                    return true;
                }else if(map == null || !map.containsKey("act")
                        || map.get("act").toString().contains("login") || map.get("act").toString().contains("default")){
//                    startActivity(new Intent(JsWebActivity.this, MainActivity.class).putExtra("index",4));
                    onLoadAndroidPage(4);
                    return true;
                }


            }

            // 联盟商家
            if (lowerUrl.contains("/lmshop.php")){
                Map map = Utils.URLRequest(url);
                if (map == null || !map.containsKey("act") || map.get("act").toString().contains("shop_index")){
//                    startActivity(new Intent(JsWebActivity.this, MainActivity.class).putExtra("index",2));
                    onLoadAndroidPage(2);
                    return true;

                }
            }

            if (lowerUrl.contains("alipayapi.php"))
            {
                paytype=1;
                Map map = Utils.URLRequest(url);
                if (map!=null)
                {
                    webPayPresenter.LoadPayMsg(map.get("out_trade_no").toString());
                }
                return true;

            }
            if (lowerUrl.contains("weixinpay.php"))
            {
                paytype=2;
                Map map = Utils.URLRequest(url);
                if (map!=null)
                {
                    webPayPresenter.LoadPayMsg(map.get("out_trade_no").toString());
                }
                return true;
            }

//            String state = "from_app=2&key=" + ConfigValue.DATA_KEY ;
//            if (!lowerUrl.contains("city.php")){
//                state = state + "&rid=" + ConfigValue.rid;
//            }
//            if(url.contains("?")){
//                url = url + "&" + state;
//            }else{
//                url = url + "?" + state;
//            }
            Log.e("JsWebActivity",url);

            return super.shouldOverrideUrlLoading(view,url);
        }

        public void onPageFinished(WebView view, String url) {

            if(loadError){
                view.setVisibility(View.GONE);
                errorView.setVisibility(View.VISIBLE);
            }else {
                view.setVisibility(View.VISIBLE);
                errorView.setVisibility(View.GONE);
            }
            CookieManager cookieManager = CookieManager.getInstance();
            String CookieStr = cookieManager.getCookie(url);
            Log.e("sunzn", "Cookies = " + CookieStr);
            super.onPageFinished(view, url);
        }



        /**
         * 是這個!!!!! 臥槽終于找着了
         * @param view
         * @param request
         * @param error
         */
        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            loadError = true;
            super.onReceivedError(view, request, error);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            loadError = true;
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
    }




    private class webChromeClient extends WebChromeClient{




        @Override
        public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) {
            return super.onJsBeforeUnload(view, url, message, result);
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {

            if (message != null && message.contains("微信")){
                loadScanView();
                return true;
            }
            return super.onJsAlert(view, url, message, result);
        }

        @Override
        public void onGeolocationPermissionsHidePrompt() {
            super.onGeolocationPermissionsHidePrompt();
            Log.i("test", "onGeolocationPermissionsHidePrompt");
        }

        //网页权限弹窗
        @Override
        public void onGeolocationPermissionsShowPrompt(final String origin,
                                                       final GeolocationPermissions.Callback callback) {
            AlertDialog.Builder builder = new AlertDialog.Builder(JsWebActivity.this);
            builder.setMessage("允许访问位置信息?");
            DialogInterface.OnClickListener dialogButtonOnClickListener = new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int clickedButton) {
                    if (DialogInterface.BUTTON_POSITIVE == clickedButton) {
                        callback.invoke(origin, true, true);
                    } else if (DialogInterface.BUTTON_NEGATIVE == clickedButton) {
                        callback.invoke(origin, false, false);
                    }
                }
            };
            builder.setPositiveButton("允许", dialogButtonOnClickListener);
            builder.setNegativeButton("拒绝", dialogButtonOnClickListener);
            builder.show();
            super.onGeolocationPermissionsShowPrompt(origin, callback);
            Log.i("test", "onGeolocationPermissionsShowPrompt");
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DataCleanManager.clearCookies(JsWebActivity.this);

    }

    private void loadScanView(){
        if (com.sanjiahantang.ythshopping.utils.Utils.NO_NETWORK_STATE == com.sanjiahantang.ythshopping.utils.Utils.isNetworkAvailable(JsWebActivity.this)) {
            return;
        }
        if (ContextCompat.checkSelfPermission(JsWebActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(new String[]{Manifest.permission.CAMERA}, 1);
            }

        } else {
            Intent itCapture = new Intent(JsWebActivity.this, CaptureActivity.class);
            itCapture.putExtra("type","home");
            startActivity(itCapture);

        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.e(TAG, "onRequestPermissionsResult");
        ToastUtil.showToast(JsWebActivity.this,"=============");
        //requestpermisiion result , permission
    }


    /**
     * Sync Cookie
     */
    private void syncCookie(Context context, String url){
        try{
//            Log.d("Nat: webView.syncCookie.url", url);

            CookieSyncManager.createInstance(context);

            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
//            cookieManager.removeSessionCookie();// 移除
//            cookieManager.removeAllCookie();
            String oldCookie = cookieManager.getCookie(url);
            if(oldCookie != null){
//                Log.d("Nat: webView.syncCookieOutter.oldCookie", oldCookie);
            }


            cookieManager.setCookie(url, "latitude=" + ConfigValue.Latitude);
            cookieManager.setCookie(url, "longitude=" + ConfigValue.Longitude);
            CookieSyncManager.getInstance().sync();
            String newCookie = cookieManager.getCookie(url);
            if(newCookie != null){
//                Log.d("Nat: webView.syncCookie.newCookie", newCookie);
            }
        }catch(Exception e){
//            Log.e("Nat: webView.syncCookie failed", e.toString());
        }
    }

}


